const { Base64 } = require("./base64.js");

// 测试环境地址：
let apiUrl = "http://testai.ssw-htzn.com";
// 生产环境地址
// let apiUrl = "https://www.aitourist.net";

// 初始化入口
module.exports.init = (app) => {
  apiUrl = `${apiUrl}/api/v1`;

  // 全局跳转小程序方法 注入到app实例
  app.navigateToMiniProgram = (paramsObj) => {
    return wx.navigateToMiniProgram({
      appId: paramsObj.appId, // APPID
      path: paramsObj.path, // path 路径
      extraData: paramsObj.extraData,
      envVersion: paramsObj.envVersion,
      success(e) {
        paramsObj.success && paramsObj.success(e);
      },
      fail(e) {
        paramsObj.fail && paramsObj.fail(e);
      },
      complete(e) {
        paramsObj.complete && paramsObj.complete(e);
      },
    });
  };

  app.header = () => {
    let header = {
      // token:
      // "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbnYiOjIsImF1dGhfc3lzIjoiZ3VpZGUiLCJ1c2VyX2lkIjoxMDAwODksInNhbHQiOiIiLCJleHAiOjE3MDczMDI3MDB9.Xu1U6N4sz-6hM325l4onmGm_xQ0bJZhmjLe5k_Cu-90",
      token: wx.getStorageSync("token") ? wx.getStorageSync("token") : "",
      accept: "application/json",
      "auth-sys": "user",
    };
    return header;
  };
  // 请求方法封装
  const request = ({ url, data, method, ...config }) =>
    new Promise((resolve, reject) => {
      const { isLoading = true } = config;
      if (!url.includes("http")) {
        url = apiUrl + url;
      }
      if (isLoading) {
        wx.showLoading({ title: "加载中", mask: true });
      }
      wx.request({
        method,
        url,
        data,
        header: app.header(),
        success: (res) => {
          const data = res.data;
          requestSuccess(app, data, config, resolve, reject);
        },
        fail(err) {
          requestFail(err, reject, config);
        },
        complete() {
          requestComplete(config);
        },
      });
    });

  // 将请求方法注入到app实例
  app.request = request;
  app.get = (url, data, config) =>
    request({ url, data, method: "GET", ...config });
  app.post = (url, data, config) =>
    request({ url, data, method: "POST", ...config });
  app.put = (url, data, config) =>
    request({ url, data, method: "PUT", ...config });
  app.delete = (url, data, config) =>
    request({ url, data, method: "DELETE", ...config });

  // 上传文件
  app.uploadFile = (url, data, config) => {
    if (!url.includes("http")) {
      url = apiUrl + url;
    }
    return uploadFile(app, url, data, config);
  };
};

// 获取apiUrl
module.exports.getApiUrl = () => apiUrl;

//上传文件
function uploadFile(app, url, data, config = {}) {
  return new Promise((resolve, reject) => {
    const { isLoading = true } = config;
    if (!url.includes("http")) {
      url = apiUrl + url;
    }
    if (isLoading) {
      wx.showLoading({ title: "加载中", mask: true });
    }
    wx.uploadFile({
      url,
      timeout: 10000,
      header: app.header(),
      ...data,
      ...config,
      success: function (res) {
        const data = JSON.parse(res.data);
        requestSuccess(app, data, config, resolve, reject);
      },
      fail(err) {
        console.log("err", err);

        requestFail(err, reject, config);
      },
      complete() {
        requestComplete(config);
      },
    });
  });
}

// 接口回调成功方法
function requestSuccess(app, data, config, resolve, reject) {
  const { isErrorToast = true, isLoading = true } = config;
  if (isLoading) {
    wx.hideLoading({
      noConflict: true,
    });
  }
  if (data.code === 20000) {
    resolve(data.data);
  } else if ([50015, 50021, 50022, 60001].includes(data.code)) {
    //如果用户登录过期，删除token
    app.globalData.token = "";
    wx.removeStorageSync("token");
    if (isErrorToast) {
      wx.showToast({
        title: data.msg || "用户信息已过期",
        icon: "none",
      });
    }
    // 用户信息过期，跳转到登录页
    setTimeout(function () {
      wx.navigateTo({
        url: "/pages/login/login",
      });
    }, 1000);
    reject(data);
  } else if (data.code === 61096) {
    // 该手机号已绑定其他微信小程序
    if (isErrorToast) {
      wx.hideLoading();
      setTimeout(() => {
        wx.showToast({
          title: data.msg || "网络错误",
          mask: true,
          icon: "none",
        });
      }, 500);
    }
    reject(data);
  } else {
    if (isErrorToast) {
      wx.showToast({
        title: data.msg || "网络错误",
        icon: "none",
      });
    }
    reject(data);
  }
}

// 接口回调失败方法
function requestFail(err, reject, config) {
  const { isLoading = true } = config;
  if (isLoading) {
    wx.hideLoading({
      noConflict: true,
    });
  }
  wx.showToast({
    title: "网络错误",
    icon: "none",
  });
  reject(err);
}

// 接口调用complete方法
function requestComplete(config) {
  const { isLoading = true } = config;
  if (isLoading) {
    wx.hideLoading({
      noConflict: true,
    });
  }
}
